package com.lindroy.androidplayer.viewmodels

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import com.elvishew.xlog.XLog
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.logic.network.repository.Repository
import com.lindroy.androidplayer.utils.*
import com.lindroy.lib_utils.extensions.getResString

/**
 * @author Lin
 * @date 2022/1/29
 * @function
 */
class LoginViewModel : ViewModel() {

    private val _loginLiveData = SingleLiveEvent<Unit>()

    private val _toRegisterLiveData = SingleLiveEvent<Unit>()

    private val _loginIllegalMessage = SingleLiveEvent<String>()

    val loginLiveData = _loginLiveData.switchMapSingle {
        Repository.login(
            userName.value.orEmpty(),
            password.value.orEmpty()
        )
    }

    val toRegisterLiveData = _toRegisterLiveData.mapSingle {  }

    val loginIllegalMessage = _loginIllegalMessage.mapSingle { it }

    val userName = MutableLiveData<String>()

    val password = MutableLiveData<String>()

    fun onLoginClick() {
        if(userName.value.orEmpty().isEmpty()){
            _loginIllegalMessage.postValue(getResString(R.string.tip_user_name_null))
            return
        }
        if(password.value.orEmpty().isEmpty()){
            _loginIllegalMessage.postValue(getResString(R.string.tip_pwd_null))
            return
        }
        _loginLiveData.postValue(Unit)
    }

    fun onToRegisterPage(){
        _toRegisterLiveData.postValue(Unit)
    }
}